package com.moodbox.server.mood.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.moodbox.server.mood.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;

@Slf4j
@Service
public class LocalUploadServiceImpl implements UploadService {

    @Value("${upload.base-path}")
    private String basePath;

    @Value("${upload.image-path}")
    private String imagePath;

    @Value("${upload.audio-path}")
    private String audioPath;

    @Value("${upload.domain}")
    private String domain;

    @Override
    public String uploadImage(MultipartFile file) {
        return uploadFile(file, imagePath);
    }

    @Override
    public String uploadAudio(MultipartFile file) {
        return uploadFile(file, audioPath);
    }

    private String uploadFile(MultipartFile file, String relativePath) {
        if (file == null || file.isEmpty()) {
            return null;
        }

        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = FileUtil.extName(originalFilename);
            String uniqueFileName = IdUtil.fastSimpleUUID() + "." + fileExtension;

            // 创建日期子目录
            String dateSubPath = LocalDate.now().toString().replace("-", "/");
            String fullPath = basePath + File.separator + relativePath + File.separator + dateSubPath;
            FileUtil.mkdir(fullPath);

            // 完整文件路径
            String filePath = fullPath + File.separator + uniqueFileName;
            File dest = new File(filePath);

            // 保存文件
            file.transferTo(dest);

            // 返回可访问的URL
            return domain + "/" + relativePath + "/" + dateSubPath + "/" + uniqueFileName;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        }
    }
} 